package com.cans.lightning.business.lowcode.service.impl;

import com.cans.lightning.business.lowcode.dto.AppTableDto;
import com.cans.lightning.business.lowcode.dto.AppTableFieldDto;
import com.cans.lightning.business.lowcode.service.api.IDBTableDoOperatorService;
import com.cans.lightning.business.lowcode.service.api.IDBTableOperatorService;
import com.google.common.collect.Maps;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.DBStyle;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author cans
 * @date 2022/11/12
 **/
@Service("dBTableOperatorService")
public class DBTableOperatorServiceImpl implements IDBTableOperatorService, SmartInitializingSingleton {

    @Resource
    private SQLManager sqlManager;
    @Resource
    private ApplicationContext applicationContext;
    private DBStyle dbStyle;
    private Map<Integer, IDBTableOperatorService> dbTableOperatorServiceMap;

    @Override
    public void createTable(AppTableDto tableDto) {
        this.getImpl().createTable(tableDto);
    }

    @Override
    public void createField(AppTableDto tableDto,AppTableFieldDto fieldDto) {
        this.getImpl().createField(tableDto,fieldDto);
    }

    @Override
    public void ifNotExitCreate(AppTableDto appTableDto, AppTableFieldDto fieldDto) {
        this.getImpl().ifNotExitCreate(appTableDto,fieldDto);
    }

    @Override
    public void afterSingletonsInstantiated() {
        this.dbStyle = sqlManager.getDbStyle();
        Map<String, IDBTableDoOperatorService> beansOfType = applicationContext.getBeansOfType(IDBTableDoOperatorService.class);
        dbTableOperatorServiceMap = Maps.newHashMap();
        for (IDBTableDoOperatorService value : beansOfType.values()) {
            dbTableOperatorServiceMap.put(value.getDbType(),value);
        }
    }

    private IDBTableOperatorService getImpl(){
        IDBTableOperatorService dbTableOperatorService = dbTableOperatorServiceMap.get(this.dbStyle.getDBType());
        if(dbTableOperatorService == null){
            throw new RuntimeException("不支持的数据库类型: " + dbStyle.getName());
        }
        return dbTableOperatorService;
    }

}
